package com.main.hotel.controller;

import com.alibaba.fastjson.JSONArray;
import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.internal.util.StringUtils;
import com.google.gson.Gson;
import com.main.hotel.config.AlipayConfig;
import com.main.hotel.entity.*;

import com.main.hotel.service.*;
import com.main.hotel.service.impl.AliPayServiceImpl;
import com.main.hotel.util.OrderUtil;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

@Controller
@RequestMapping("/customer")
public class CustomerController {
  @Autowired
  private CustomerService customerService;

  @Autowired
  private CustomerTokenService customerTokenService;
  @Autowired
  private AliPayServiceImpl aliPayService;
  @Autowired
  private RoomTypeService roomTypeService;
  @Autowired
  private OrderInfoService orderInfoService;

  @Autowired
  private FeedbackService feedbackService;

  @RequestMapping("/getCustomerById")//访问路径：http://localhost:8080/customer/getCustomerById?id=1
  @ResponseBody
  public String getCustomerById(Integer id) {
    //System.out.println(id);
    Customer customer = customerService.getCustomerById(id);
    Gson gson = new Gson();
    String jsonUser = gson.toJson(customer);
    System.out.println(jsonUser);
    return jsonUser;

  }


  @RequestMapping("/confirm")//访问路径：
  @ResponseBody
  public Result confirmCustomer(Customer customer) {
    //System.out.println(id);
    Result result = new Result();
    System.out.println(customer.getPassword() + "   " + customer.getPhone() + "   88");
    Customer customer2 = customerService.confirmCustomer(customer.getPhone(), customer.getPassword());
    System.out.println(customer2.toString() + "  99");
    if (customer2 == null)
      return null;
    result.setCustomer_id(customer2.getCustomer_id());
    CustomerToken customerToken = customerTokenService.findByCustomerId(customer2.getCustomer_id());
    //为生成Token准备
    String TokenStr = "";
    Date date = new Date();
    int nowtime = (int) (date.getTime() / 1000);
    //生成Token
    TokenStr = creatToken(customer2, date);
    if (null == customerToken) {
      //第一次登陆
      customerToken = new CustomerToken();
      customerToken.setToken(TokenStr);
      customerToken.setBuild_time(nowtime);
      customerToken.setCustomer_id(customer2.getCustomer_id());
      customerTokenService.addToken(customerToken);
    } else {
      //登陆就更新Token信息
      TokenStr = creatToken(customer2, date);
      customerToken.setToken(TokenStr);
      customerToken.setBuild_time(nowtime);
      customerTokenService.updataToken(customerToken);
    }
    result.setTokenString(TokenStr);
    return result;
  }

  //生成Token信息方法（根据有效的用户信息）
  private String creatToken(Customer customer, Date date) {
    SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
    JwtBuilder builder = Jwts.builder().setHeaderParam("typ", "JWT") // 设置header
      .setHeaderParam("alg", "HS256").setIssuedAt(date) // 设置签发时间
      .setExpiration(new Date(date.getTime() + 1000 * 60 * 60 * 24 * 3))
      .claim("customer_id", String.valueOf(customer.getCustomer_id())) // 设置内容
      .setIssuer("lws")// 设置签发人
      .signWith(signatureAlgorithm, "dahao"); // 签名，需要算法和key
    String jwt = builder.compact();
    return jwt;


  }

  @RequestMapping("/addOrder")
  @ResponseBody
  public String addOrder(OrderInfo orderInfo) {
    Date date = new Date();
    String order_id = OrderUtil.getOrderId();
    orderInfo.setOrder_id(order_id);
    orderInfo.setCreateTime(date);
    float order_cost=roomTypeService.getRoomPrice(orderInfo.getRoomType())*orderInfo.getOrder_days();
   // String cost=String.valueOf((int)(order_cost));
    // orderInfo.setOrder_status(0);
    orderInfo.setOrder_cost(order_cost);
   // orderInfo.setOrder_date(date);
    //orderInfo.setRoom_id(1);
    int result = customerService.addOrder(orderInfo);
    if (result == 1)
      return "success";
    else
      return "false1";
  }


  @RequestMapping(value = "/pay")
  @ResponseBody
  public String aliPay(OrderInfo orderInfo) {
    String order_id = OrderUtil.getOrderId();
    orderInfo.setOrder_id(order_id);
    System.out.println(orderInfo.getRoomType()+"  66");
    float order_cost=roomTypeService.getRoomPrice(orderInfo.getRoomType())*orderInfo.getOrder_days();
    String cost=String.valueOf((int)(order_cost));
   // orderInfo.setOrder_status(0);
    orderInfo.setOrder_cost(order_cost);
    Date date = new Date();
    orderInfo.setCreateTime(date);
    //orderInfo.setOrder_date(date);
    //orderInfo.setRoom_id(1);
    int result = customerService.addOrder(orderInfo);
    if(result==0)
      return "false";
    return aliPayService.alipay(orderInfo.getOrder_id(), orderInfo.getRoomType(), cost, orderInfo.getRemark(),
      AlipayConfig.NOTIFY_URL,orderInfo.getFoo());

  }


  @RequestMapping(value = "/alipay/orderNotify", method = RequestMethod.POST)
  public void orderNotify(HttpServletResponse response, HttpServletRequest request) throws Exception {
    Map<String, String> params = new HashMap<String, String>();
    Map requestParams = request.getParameterMap();
    for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
      String name = (String) iter.next();
      String[] values = (String[]) requestParams.get(name);
      String valueStr = "";
      for (int i = 0; i < values.length; i++) {
        valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
      }
      // 乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
      // valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk");
      params.put(name, valueStr);
    }
    // 获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以下仅供参考)//
    // 商户订单号
    String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");
    // 支付宝交易号
    String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");
    // 交易状态
    String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"), "UTF-8");
    // 付款金额
    BigDecimal payMoney = new BigDecimal(request.getParameter("total_amount"));
    // 到账金额
    BigDecimal receiptMoney = new BigDecimal(request.getParameter("receipt_amount"));
    // 获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以上仅供参考)//https://docs.open.alipay.com/270/
    boolean verify_result = AlipaySignature.rsaCheckV1(params, AlipayConfig.ALIPAY_PUBLIC_KEY,
      AlipayConfig.CHARSET, "RSA2");

    if (verify_result) {// 验证成功
      // ——请根据您的业务逻辑来编写程序（以下代码仅作参考）——
      if (trade_status.equals("TRADE_FINISHED")) {
        // 判断该笔订单是否在商户网站中已经做过处理
        // 如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
        // 请务必判断请求时的total_fee、seller_id与通知时获取的total_fee、seller_id为一致的
        // 如果有做过处理，不执行商户的业务程序
        // 注意：
        // 如果签约的是可退款协议，退款日期超过可退款期限后（如三个月可退款），支付宝系统发送该交易状态通知
        // 如果没有签约可退款协议，那么付款完成后，支付宝系统发送该交易状态通知。
      } else if (trade_status.equals("TRADE_SUCCESS")) {
        // 支付交易成功  处理订单
        int r=orderInfoService.updateOrder(out_trade_no);
        System.out.println("交易成功");
      }
    } else {// 验证失败
      System.out.println("验证失败");
    }

  }

  @RequestMapping(value = "/returnUrl", method = RequestMethod.GET)
  public String returnUrl(int foo) throws Exception {
//    return "redirect:/index2?foo="+foo;
    return "redirect:/personal";
  }

  @RequestMapping("/customerInfo")
  @ResponseBody
  public Customer getCustomerById(int customer_id) {
    Customer customer = customerService.getCustomerById(customer_id);
    return customer;
  }

  @RequestMapping("/cancel")

  public String cancelOrder(String order_id) throws IOException, AlipayApiException {
   String result= customerService.cancelOrder(order_id);

    return "redirect:/personal";

  }

  @RequestMapping("/update")
@ResponseBody
  public String updateCustomer(Customer customer) throws IOException, AlipayApiException {
   // String result= customerService.cancelOrder(order_id);
    int result=customerService.updateCustomer(customer.getPassword(),customer.getPhone());
    if(result==1)
      return "success";
    else
      return "false";
  }

  @RequestMapping("/feedback")
  @ResponseBody
  public String feedback(String feedback,int customer_id) throws IOException, AlipayApiException {
    Date date=new Date();
    System.out.println(feedback);
    Feedback feedback1=new Feedback();
    feedback1.setFeedback(feedback);
    feedback1.setCreateDate(date);
    feedback1.setCustomer_id(customer_id);
    int result=feedbackService.addFeedback(feedback1);
    if(result==1)
      return "success";
    else
      return "false";
  }
}
